<script>
	const httpRequest = require("@/common/httpRequest.js")
	import WebSocket from '@/common/websocket.js' //websocket封装
	const Screen = uni.requireNativePlugin('Yam-Screen');
	import silenceUpdate from '@/uni_modules/rt-uni-update/js_sdk/silence-update.js' //引入静默更新
	// #ifdef APP-PLUS
	const TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
	const TUICallingEvent = uni.requireNativePlugin('globalEvent');
	const ox = uni.requireNativePlugin('Jiang-OxVideoRecorder');
	// #endif
	export default {
		globalData: {
			videopage: "/pages/homepage",
			xsyhq: false, //显示优惠券
			myuser_id: "",
			firend_id: "",
			callMediaType: "", //语音通话(callMediaType = 1)、视频通话(callMediaType = 2)
			thsetinterval: null, //通话定时器
			islogin: false,
		},
		data() {
			return {
				websocket: null,
				is_contact: false,
				roomID: ""
			}
		},

		onLaunch: function() {
			this.getSystem()
			ox.clearCache(); //清理缓存
			ox.unzipFilter({
				filters: [{
						name: '纯真',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/001.zip'
					},
					{
						name: '清新',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/002.zip'
					}, {
						name: '桃花',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/003.zip'
					}, {
						name: '红润',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/004.zip'
					}, {
						name: '心境',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/005.zip'
					}, {
						name: '香氛',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/006.zip'
					}, {
						name: '草木绿',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/007.zip'
					}, {
						name: '俏皮',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/008.zip'
					}, {
						name: '童话',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/009.zip'
					}, {
						name: '棉花糖',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/0010.zip'
					}, {
						name: '初夏',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/011.zip'
					}, {
						name: '天真',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/012.zip'
					}, {
						name: '奇妙',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/013.zip'
					}, {
						name: '欣喜',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/014.zip'
					}, {
						name: '爱乐',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/015.zip'
					}, {
						name: '温暖',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/016.zip'
					}, {
						name: '星期四',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/017.zip'
					}, {
						name: '可爱',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/018.zip'
					}, {
						name: '超脱',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/019.zip'
					}, {
						name: '雪花',
						zipPath: 'https://kuaixun-1323241856.cos.ap-nanjing.myqcloud.com/%E6%BB%A4%E9%95%9C/020.zip'
					},
				]
			});
			this.globalData.xsyhq = true
			this.userinfofn()
			// 通话方式 1语音通话已取消，2视频通话已取消，3语音通话结束，4视频通话结束
			// 音视频通话监听
			TUICallingEvent.addEventListener('onError', (res) => { //通话过程中错误回调
				this.roomID = ""
				console.log('//通话过程中错误回调》》》onError', JSON.stringify(res));
			});
			TUICallingEvent.addEventListener('onCallCancelled', (res) => { //通话取消的回调
				this.roomID = ""
				console.log('//通话取消回调》》》onCallCancelled', JSON.stringify(res));
				if (this.globalData.firend_id) { //如果存在对方的id了就证明是我向对方打的电话,这里是一直没有接通或者取消了回走
					let text = this.globalData.callMediaType == 1 ? "语音通话已取消" : "视频通话已取消"
					this.bodaFn(this.globalData.firend_id, text)
					console.log(this.globalData.firend_id, "进来了");
				}
			});
			TUICallingEvent.addEventListener('onCallBegin', (res) => { //通话接通的回调
				console.log('//通话开始回调》》》onCallBegin', res);
				this.roomID = res.roomID
				if (this.globalData.firend_id) { //如果存在对方的id了就证明是我向对方打的电话
					this.addUserTh(res.roomID) //创建语音视频记录
				} else { //这里是非发起人接听电话的时候的校验，判断当前人是否能接听电话不能的话直接挂断电话
					this.checkYyspRule(res.roomID)
				}
			});

			TUICallingEvent.addEventListener('onCallEnd', (res) => { //通话结束的回调
				console.log('//通话结束回调》》》onCallEnd', JSON.stringify(res));
				// 示例使用
				this.roomID = ""
				let seconds = Number(res.totalTime).toFixed(0); // 125秒
				let formattedTime = this.secondsToMinutesSeconds(seconds);
				if (this.globalData.firend_id) {
					let text = this.globalData.callMediaType == 1 ? "语音通话 " + formattedTime : "视频通话 " +
						formattedTime
					this.bodaFn(this.globalData.firend_id, text)
				}
				this.getthdetail(res.roomID, formattedTime)
				clearInterval(this.globalData.thsetinterval)
				this.globalData.thsetinterval = null
				this.globalData.firend_id = ""
			});
		},
		onLoad() {
			uni.setStorageSync("isjump", false)
			// if (httpRequest.checkIsLogin() && uni.getSystemInfoSync().platform != 'ios') { //已经登陆,创建websocket连接
			// 	this.websocketStart()
			// }
		},
		onShow: function() {
			uni.setStorageSync("isjump", false)
			if (httpRequest.checkIsLogin()) { //已经登陆,创建websocket连接
				this.websocketStart()
			}
			//#ifdef APP-PLUS
			// 获取本地应用资源版本号
			plus.runtime.getProperty(plus.runtime.appid, (inf) => {
				console.error(uni.getSystemInfoSync().platform, inf.versionCode);
				//获取服务器的版本号
				uni.request({
					url: 'https://kuaixun.yongshunqiyuewangluo.com/api/index/getDownloadUrl', //示例接口
					data: {
						version_type: uni.getSystemInfoSync().platform, //android或者ios
						edition_number: inf.versionCode // 打包时manifest设置的版本号 
					},
					success: (res) => {
						console.log("版本更新", res.data);
						//res.data.xxx根据后台返回的数据决定（我这里后端返回的是data），所以是res.data.data 
						//判断后台返回版本号是否大于当前应用版本号 && 是否发行 （上架应用市场时一定不能弹出更新提示）
						if (Number(res.data.data.edition_number) > Number(inf.versionCode) && res
							.data.data.edition_issue == 1) {
							//如果是wgt升级，并且是静默更新 （注意！！！ 如果是手动检查新版本，就不用判断静默更新，请直接跳转更新页，不然点击检查新版本后会没反应）
							if (res.data.data.package_type == 1 && res.data.data.edition_silence ==
								1) {
								//调用静默更新方法 传入下载地址
								silenceUpdate(res.data.data.edition_url)
							} else {
								//跳转更新页面 （注意！！！如果pages.json第一页的代码里有一打开就跳转其他页面的操作，下面这行代码最好写在setTimeout里面设置延时3到5秒再执行）
								uni.navigateTo({
									url: '/uni_modules/rt-uni-update/components/rt-uni-update/rt-uni-update?obj=' +
										JSON.stringify(res.data.data)
								});
							}

						} else {
							// 如果是手动检查新版本 需开启以下注释
							/* uni.showModal({
							    title: '提示',
							    content: '已是最新版本',
							    showCancel: false
							}) */
						}
					}
				})
			});
			//#endif
			if (this.globalData.islogin) {
				this.globalData.myuser_id = uni.getStorageSync("user_id")
			} else {
				this.userinfofn()
			}
			if (httpRequest.checkIsLogin() && this.is_contact === false) { //已经登陆,创建websocket连接
				this.websocketStart()
			}
		},

		onHide() {
			this.websocket.close()
		},
		onUnload: function() {
			uni.setStorageSync("isjump", false)
			uni.$off("webscoketclosedFn")
			console.log('App Hide')
			this.is_contact = false
			this.websocket.close()
		},
		methods: {
			checkYyspRule(thbo) {
				console.log("房间id", thbo);
				httpRequest.request('/api/user/checkYyspRule', 'GET', {
					thbo
				}).then(resp => {
					console.log("房间返回数据", resp);
					if (resp.code == -1) {
						this.checkYyspRule(thbo)
						return false
					}
					if (resp.code != 1) {
						this.jsRoom(this.roomID) //解散房间
						setTimeout(() => {
							httpRequest.toast(resp.msg)
						}, 1000)
						return false
					}
					this.clearYyJbnum(this.roomID)
					this.globalData.thsetinterval = setInterval(() => {
						this.clearYyJbnum(this.roomID)
						console.error("______________________走了一次定时器");
					}, 60000)
				})
			},
			jiepingstop() {
				//检查权限并授权
				// Screen.checkPermission(function(res) {
				// 	console.log(res);
				// });
				let that = this
				if (uni.getSystemInfoSync().platform == 'android') {
					//打开相册、图片预览或其他原生界面时开启防录屏，仅android支持
					Screen.setAntiActivityList([
						"io.dcloud.feature.nativeObj.photoview.PhotoActivity",
						//"io.dcloud.WebAppActivity",
						//"io.dcloud.ProcessMediator",
						//"io.dcloud.WebviewActivity",
						"com.tencent.qcloud.tuicore.permission.PermissionActivity",
						"com.tencent.qcloud.tuicore.util.PermissionRequester$PermissionActivity",
						"com.tencent.qcloud.tuikit.tuicallkit.view.CallKitActivity",
						"com.tencent.qcloud.tuikit.tuicallkit.extensions.inviteuser.SelectGroupMemberActivity",
						"com.tencent.qcloud.tuikit.tuicallkit.base.BaseCallActivity",
						"com.dmcbig.mediapicker.PickerActivity",
						"com.dmcbig.mediapicker.PreviewActivity",
						"io.dcloud.feature.gallery.imageedit.IMGEditActivity" //,
						//"io.dcloud.sdk.activity.WebViewActivity",
						//"com.taobao.weex.devtools.toolbox.PerformanceActivity",
						//"com.blankj.utilcode.util.PermissionUtils$PermissionActivity"
					]);
					//设置录屏通知配置，仅android支持
					Screen.setRecordConfig({
						contentTitle: "快讯",
						contentText: "正在录屏"
					});
				}

				if (uni.getSystemInfoSync().platform == 'ios') {
					//判断是否在屏幕录制
					var ret = Screen.isCaptured(); //true:正在录制 false：停止录制
					//监听截屏录屏回调
					Screen.setScreenCallback(function(res) {
						console.log("监听截屏回调事件", res);
						if (res.type == "onScreenShot") {
							if (that.roomID) {
								that.jsRoom(that.roomID) //解散房间
								that.roomID = ""
							}
							//监听截屏回调事件
							uni.showModal({
								content: "为了更好的保护您的隐私，快讯禁止使用截屏录屏功能"
							})
						} else if (res.type == "onScreenCapturedDidChange") {
							//监听屏幕录制回调事件
							var isCaptured = res.data; //true:正在录制 false：停止录制
						}
					});
				}
				Screen.openAntiRecordScreen();
			},
			secondsToMinutesSeconds(seconds) {
				var minutes = Math.floor(seconds / 60); // 获取分钟
				var secondsRemain = seconds % 60; // 获取剩余秒数
				// 返回格式化的字符串
				return (minutes < 10 ? "0" : "") + minutes + ":" + (secondsRemain < 10 ? "0" : "") + secondsRemain;
			},
			// 拨打电话结束给好友发消息
			bodaFn(toid, text) { //发送消息
				// 语音通话(callMediaType = 1)、视频通话(callMediaType = 2)
				let system = uni.getSystemInfoSync()
				let version_code = system.appVersionCode
				let platform = system.platform
				let data = {
					mine: {
						id: uni.getStorageSync("user_id"),
						content: text,
						data_type: this.globalData.callMediaType == 1 ? 7 : 6,
					},

					to: {
						id: toid,
						type: "friend"
					},
					client_id: uni.getStorageSync("client_id"),
					version_code,
					platform
				}
				console.log("进来了", data);
				httpRequest.request('/webim/Friends_Message/add', 'POST', data).then(res => {
					// if(res.code==403){
					// 	this.websocketStart()
					// }else{
					uni.$emit('calltelephoneFn', res.data)
					// }
				})
			},
			websocketStart() {
				this.websocket = new WebSocket("wss://kuaixun.yongshunqiyuewangluo.com:8282");
				this.websocket.connect()
				this.websocket.onMessage(result => {
					this.is_contact = true
					console.log('app.js收到服务器内容：' + result.data);
					uni.$emit('updatechatFnte', "")
					uni.$emit('updatechatFnteList', "")
				})
			},

			webclosed() {
				console.log("关闭");
				this.websocket.close()
			},
			getSystem() { //获取系统配置
				let _this = this
				httpRequest.request('/api/index/getConfigInfo', 'GET', {}).then(res => {
					console.log("惊雷》》》》》》", res)
					let data = {
						share_url: res.data.share_url,
						share_title: res.data.share_title,
						share_des: res.data.share_des,
						share_logo: res.data.share_logo,
					}
					uni.setStorageSync("shareMsg", data)
				})
				let system = uni.getSystemInfoSync()
				let version_code = system.appVersionCode
				let platform = system.platform
				httpRequest.request('/api/index/checkApply', 'GET', {
					platform,
					version_code
				}).then(res => {
					if (!res.data) { //如果不是审核版本再掉禁止截屏功能
						this.jiepingstop()
					}
				})
			},
			addUserTh(thbo) {
				httpRequest.request('/api/user/addUserTh', 'GET', {
					thbo,
					to_user_id: this.globalData.firend_id,
					chat_type: this.globalData.callMediaType
				}).then(res => {
					console.log("创建通话记录", res);
				})
			},
			clearYyJbnum(thbo) { //音视频通话扣除金币
				httpRequest.request('/api/user/clearYyJbnum', 'GET', {
					thbo
				}).then(res => {
					if (res.code == 0) {
						this.jsRoom(thbo) //解散房间
					}
					console.log("扣钱接口", res);
				})
			},

			jsRoom(room_id) {
				httpRequest.request('/api/user/jsRoom', 'GET', {
					room_id
				}).then(res => {
					console.log("解散房间", res);
				})
			},
			getthdetail(thbo, time) { //获取通话记录，查看获得了/扣除了多少金币
				httpRequest.request('/api/user/getUserTh', 'GET', {
					thbo
				}).then(res => {
					console.log("获取通话记录，查看获得了/扣除了多少金币", time);
					console.log("获取通话记录，查看获得了/扣除了多少金币", res);
					let dataobj = {
						xf: res.data.user_id == this.globalData.myuser_id ? true : false,
						time: time,
						xfjb: res.data.jb_num,
					}
					uni.navigateTo({
						url: '/pages_message/popup?msg=' + encodeURIComponent(JSON.stringify(dataobj))
					})
				})
			},
			userinfofn() {
				if (!httpRequest.checkIsLogin()) {
					this.globalData.islogin = false
					return false
				}
				httpRequest.request('/api/user/getUserSig', 'GET', {}).then(res => {
					this.globalData.islogin = true
					console.log("获取用户信息成功", res.data);
					let user_id = uni.getStorageSync("user_id")
					this.tuicallkitLogin(user_id, res.data.userSig)
				})
				// httpRequest.request('/api/user/profile', 'GET', {online:1}).then(res => {})
			},

			tuicallkitLogin(userId, userSig) {
				console.log(userId, userSig, "555555555555555555555555555")
				const options = {
					// SDKAppID: 1400796881, // 请替换为步骤一取到的 SDKAppID
					// userID: "123", // 请替换为您的 UserID
					// userSig: "eJwtzEELgjAYxvHv8l4N2*bUNejUpcAstNg53LIXmQ21FUbfPVCPz**B-xcuWRl604EEFhJYTRu1aQe848SURQv3urk5hxok5YSkm0QIOj8DWgOSpjSmcRoLNqv5OOwMyCghZClgDRJUw062uhL*6gOfH8vgkSnVrt**D4wYzzwfi93*UDxtzbfw*wOpJy8m", // 您可以在控制台中计算一个 UserSig 并填在这个位置
					SDKAppID: 1600021546, // 请替换为步骤一取到的 SDKAppID
					userID: userId.toString(), // 请替换为您的 UserID
					userSig: userSig.toString(), // 您可以在控制台中计算一个 UserSig 并填在这个位置
				};
				TUICallKit.login(options, (res) => {
					if (res.code === 0) {
						console.log('login success》》》》》》腾讯云音视频连接成功');
					} else {
						console.log(`login failed, error message = ${res.msg}`);
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "colorui/main.css";
	@import "colorui/icon.css";
	@import "uview-ui/index.scss";
	@import url("static/css/main1.css");
	@import url("static/css/last.scss");

	/deep/.u-navbar__content__left {
		width: 80%;
	}
</style>